package com.example.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.example.clients.UserClient;
import com.example.domain.Book;
import com.example.domain.User;
import com.example.domain.UserResult;
import com.example.service.IBookService;
import com.example.untils.RedisConstants;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/book")
public class BookController {
    @Autowired
    private IBookService iBookService;
    @Autowired
    private StringRedisTemplate template;
    //分页查询
    @PostMapping("/PageList/{currentPage}/{pageSize}")
    public IPage<Book> listPage(@PathVariable int currentPage,@PathVariable int pageSize, @RequestBody Book book){
        IPage<Book> ipage=new Page<>(currentPage,pageSize);
        LambdaQueryWrapper<Book> wrapper=new LambdaQueryWrapper<>();
        wrapper.like(Strings.isNotEmpty(book.getName()),Book::getName,book.getName());
        wrapper.like(Strings.isNotEmpty(book.getAddress()),Book::getAddress,book.getAddress());
        IPage<Book> page = iBookService.page(ipage, wrapper);
        return page;
    }
    //id查询
    @GetMapping("/selectId/{id}")
    public Book selectId(@PathVariable Long id){
        String key= RedisConstants.SELECTID_BOOK_KEY +id;
        String bookJson = template.opsForValue().get(key);
        if(bookJson!=null){
            //hutool工具方法：JSON转对象
            Book book = JSONUtil.toBean(bookJson, Book.class);
            return book;
        }
        //如果redis不存在的情况
        Book res = iBookService.getById(id);
        //如果mysql数据库中的数据也为空
        if(res==null){
            template.opsForValue().set(key,JSONUtil.toJsonStr(res),RedisConstants.SELECTID_NULL_TTL, TimeUnit.MINUTES);
            return res;
        }
        template.opsForValue().set(key,JSONUtil.toJsonStr(res),RedisConstants.SELECTID_BOOK_TTL, TimeUnit.MINUTES);
        return res;
    }

    //行修改
    @PostMapping("/updateRow")
    @Transactional
    public Boolean selectId(@RequestBody Book book){
        if(book.getId()==null){
            return false;
        }
        String key= RedisConstants.SELECTID_BOOK_KEY +book.getId();
        boolean flag = iBookService.updateById(book);
        template.opsForValue().set(key,JSONUtil.toJsonStr(book),RedisConstants.SELECTID_BOOK_TTL, TimeUnit.MINUTES);
        return flag;
    }
    //行删除
    @DeleteMapping("/deleteRow/{id}")
    @Transactional
    public Boolean deleteRow(@PathVariable Long id){
        if(id==null){
            return false;
        }
        String key= RedisConstants.SELECTID_BOOK_KEY +id;
        boolean flag = iBookService.removeById(id);
        template.delete(key);
        return flag;
    }
    //多行删除
    @PostMapping("/delete")
    @Transactional
    public Boolean delete(@RequestBody List<Book> list){
        List<Long> ids=new ArrayList<>();
        for (Book book : list) {
            ids.add(book.getId());
        }
        boolean flag = iBookService.removeByIds(ids);
        return flag;
    }
    //添加数据
    @PutMapping("/addRow")
    public Boolean addRow(@RequestBody Book book){
        boolean flag = iBookService.save(book);
        return flag;
    }
    @Autowired
    private UserClient userClient;

    //获取用户信息
    @GetMapping("/gainUser")
    public UserResult gainUser(){
        return userClient.gainUser();
    }
    //微服务测试
    @GetMapping("/test/{username}")
    public User testServer(@PathVariable String username){
        User user = userClient.testServer(username);
        System.out.println(user);
        return user;
    }
}
